<?php
include_once('config/config.php');

// 判断是否登录函数
$LoginAdmin = checkAuth();

$id = $_GET['id'] ?? 0;

// 判断是否有post请求
if ($_POST) {
    // 接收参数
    $newname = trim($_POST['newname']) ?? '';
    $oldpassword = trim($_POST['oldpassword']) ?? '';
    $newpassword = trim($_POST['newpassword']) ?? '';
    $repass = trim($_POST['repass']) ?? '';

    $sql = "SELECT `salt`,`password`,`avatar` FROM `pre_admin` WHERE `id` = '$id'";
    $resSql = find($sql);


    // 检查用户名是否为空
    if (empty($newname)) {
        showMsg('请输入用户名');
    }

    // 判断参数是否为空
    if (empty($password) && empty($repass) && empty($newpassword)) {
        showMsg('请输入密码或确认密码为空!');
    }

    // 原密码
    $password = md5($oldpassword . $resSql['salt']);

    // 判断原密码是否正确
    if ($password !== $resSql['password']) {
        showMsg('原密码错误');
    }
    // 判断新密码和确认密码是否一致
    if ($newpassword !== $repass) {
        showMsg('新密码和确认密码不一致');
    }


    // 判断是否有文件上传，没有就不执行下去
    if ($_FILES['avatar']['error'] == 0) {
        // 执行文件上传
        // 处理上传头像
        $res = build_upload('avatar');

        if ($res['code'] == 0) {
            showMsg($res['msg']);
        }
        // 判断头像是否修改
        if($res['data'] != $resSql['avatar']){
            // 删除旧头像文件
            $url = '.'.$resSql['avatar'];
            unlink($url);
            $avatar =  $res['data'] ?? null;
        }
        
    }


    // 生成密码盐
    $salt = build_ranstr();

    if (empty($salt)) {
        showMsg('密码盐未知!');
    }

    // 生成密码并加密，重新赋值
    $newpassword = md5($newpassword . $salt);

    // 封装数据
    $data = [
        'username' => $newname,
        'password' => $newpassword,
        'salt' => $salt,
        'avatar' => $avatar
    ];
    // print_r($data);
    // exit;

    // 添加数据
    $result = upd('admin', $data, $id);

    if ($result['code'] === 1) {
        showMsg('更新成功', 'adminList.php');
    } else {
        @is_file('.' . $data['avatar']) && @unlink('.' . $data['avatar']);
        echo $result['data'];
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include_once('common/meta.php'); ?>
</head>
<style>

</style>

<body>

    <?php include_once('common/header.php'); ?>

    <?php include_once('common/menu.php'); ?>

    <div class="content">
        <div class="header">
            <h1 class="page-title">编辑用户</h1>
        </div>
        <ul class="breadcrumb">
            <li><a href="adminList.php">adminList</a> <span class="divider">/</span></li>
            <li class="active">adminEdit</li>
        </ul>

        <div class="container-fluid">
            <div class="row-fluid">

                <div class="btn-toolbar">
                    <button class="btn btn-primary" onClick="location='adminList.php'"><i class="icon-list"></i> 管理员列表</button>
                    <div class="btn-group">
                    </div>
                </div>

                <div class="well">
                    <div id="myTabContent" class="tab-content">
                        <div class="tab-pane active in" id="home">
                            <form method="post" enctype="multipart/form-data">

                                <label>用户名</label>
                                <input type="text" name="newname" required class="input-xxlarge">
                                <span id="username"></span>

                                <label>旧密码</label>
                                <input type="password" name="oldpassword" required class="input-xxlarge">

                                <label>新密码</label>
                                <input type="password" name="newpassword" required class="input-xxlarge">

                                <label>确认密码</label>
                                <input type="password" name="repass" required class="input-xxlarge">

                                <label>新头像</label>
                                <input type="file" name="avatar" id="avatar" hidden class="input-xxlarge">

                                <img src="/assets/images/upload.png" style="width: 200px;height:200px" id="img" alt="">

                                <label></label>
                                <input class="btn btn-primary" type="submit" value="提交" />
                            </form>
                        </div>
                    </div>
                </div>

                <?php include_once('common/footer.php'); ?>

            </div>
        </div>
    </div>

</body>

</html>

<?php include_once('common/script.php'); ?>

<script>
    // 点击图片等于点击上传框
    $('#img').click(function() {
        $('#avatar').click();
    });

    // 监听上传框的值有变化时触发事件
    $('#avatar').change(function() {
        let file = $(this)[0].files[0];


        if (file) {
            // 创建一个FileReader对象,
            // 该对象是用来读取文件中的数据的
            let Reader = new FileReader();
            // 读取文件中的数据,方法会将文件转换为DataURL格式，这是一种将文件内容编码为URL的字符串表示形式的方法。
            Reader.readAsDataURL(file);

            // 读取操作完成后会触发onload事件（当reader加载完，触发事件）
            Reader.onload = function() {
                $('#img').attr('src', Reader.result);
            }

        }
    });

    // 监听用户名的值有变化所触发的事件
    $('input[name="newname"]').change(function() {

        let that = $(this);

        let newname = $.trim(that.val());

        if (!newname) {
            $('#username').text('请输入新用户名').css({
                color: 'red'
            });
            $(this).css({
                borderColor: '#e9322d',
                boxShadow: '0 0 6px #f8b9b7'
            });
            return;
        }

        $.ajax({
            type: 'post',
            url: 'api.php',
            data: {
                newname,
                action: 'check_newname'
            },
            dataType: 'json',
            success: function(res) {
                if (res && res.code === 1) {
                    $('#username').text(res.msg).css({
                        color: 'green'
                    });
                    that.css({
                        borderColor: 'unset',
                        boxShadow: 'unset'
                    });
                    return;
                } else {
                    $('#username').text('用户名已存在').css({
                        color: 'red'
                    });
                    that.css({
                        borderColor: '#e9322d',
                        boxShadow: '0 0 6px #f8b9b7'
                    });
                    return;
                }
            }
        })
    });
</script>